package com.hsb.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.hsb.entity.Book;
import com.hsb.parsing.ParseByKeyWord;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

public class ElasticSearchUtil {
    private static final RestHighLevelClient client;

    static {
        //创建连接
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));
    }
    //根据关键字查询
    public static ArrayList<Map<String,Object>> queryByKeyword(String keyword,int from,int size) {
        SearchRequest request = new SearchRequest("book");
        //构建查询请求体
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchPhraseQuery("name",keyword));//匹配词组查询
        //构建高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");//设置高亮字段
        highlightBuilder.requireFieldMatch(false);//设置多个高亮字段
        highlightBuilder.preTags("<font color='red'>");//设置标签前缀
        highlightBuilder.postTags("</font>");//设置标签后缀

        //设置高亮构建对象
        searchSourceBuilder.highlighter(highlightBuilder);

        //分页查询
        searchSourceBuilder.from(from);//当前页索引(每页第一条数据的顺序号)=（当前页-1）*size
        searchSourceBuilder.size(size);//每页大小
        request.source(searchSourceBuilder);

        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //查询返回结果
        SearchHits hits = response.getHits();
        ArrayList<Map<String,Object>> books = new ArrayList<>();
        for (SearchHit hit : hits) {
            //获取高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (name!=null){
                String fragments = Arrays.toString(name.fragments());
                sourceAsMap.put("name",fragments.substring(1,fragments.length()-1));
            }
            books.add(sourceAsMap);
        }
//        try {
//            client.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return books;
    }

    //创建索引
    public static boolean createIndex(String index){
        //创建索引
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse response = null;
        try {
            response = client.indices().create(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response!=null)return response.isAcknowledged();
        return false;
    }

    //批量导入数据
    public static boolean creatDocBatch(String index,ArrayList<Book> list){
        //创建索引
        BulkRequest request = new BulkRequest();
        //获取数据
//        ArrayList<Book> books = null;
//        try {
//            books = ParseByKeyWord.parse("python");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        for (int i=0;i<list.size();i++){
            try {
                request.add(new IndexRequest(index).source(new JsonMapper().writeValueAsString(list.get(i)), XContentType.JSON));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        BulkResponse response = null;
        try {
            response = client.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response!=null) return !response.hasFailures();
        return false;
    }

}
